package com.itheima.edu.info.manager.service;

import com.itheima.edu.info.manager.dao.BaseStudentDao;
import com.itheima.edu.info.manager.dao.OtherStudentDao;
import com.itheima.edu.info.manager.domain.Option;
import com.itheima.edu.info.manager.domain.Student;
import com.itheima.edu.info.manager.factory.StudentFactory;

import java.io.*;
import java.net.Socket;
import java.util.*;


public class StudentService implements Runnable {

    String delId;

    private Socket socket;




    //业务员指挥库管从学生工厂获取学生对象
    private BaseStudentDao dao = StudentFactory.getStudentDao();

    public StudentService(Socket socket) {
        this.socket = socket;
    }


    //业务员中的添加功能
    public void addStudent(String stuStr) throws IOException {
        String[] split = stuStr.split(",");
        Student stu = new Student(split[0], split[1], split[2], split[3]);
        //将库管的添加结果退回给contriller客服
        boolean flag = dao.addStudent(stu);
        //将结果响应给客户端
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(flag + "");
        bw.newLine();
        bw.flush();
        bw.close();
        socket.close();

    }


    //业务员中的判断学号是否存在功能
    public void isExists(String id) throws IOException {
        //1拿到系统中已有的的索引学号信息
        //1.1指挥库管将系统中索引学生信息查找出来
        Student[] allStudents = dao.findAllStudent();
        //2.拿要校验的id去已有的学号中遍历查找
        //2.1先假设要查找的id不存在
        boolean flag = false;

        //2.2遍历已有的学生信息
        for (int i = 0; i < allStudents.length; i++) {
            //2.3拿到每一个学生对象的学号
            Student stu = allStudents[i];
            //2.4当前索引位置的学生不为null，并且该学生的学号和要查找的学号一致时，修改标记
            if (stu != null && stu.getId().equals(id)) {
                flag = true;
            }
        }

        //将结果响应给客户端
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(flag + "");
        bw.newLine();
        bw.flush();
        bw.close();
        socket.close();

    }


    //业务员中的查看所有学生功能
    public void findAllStudent() {
        //获取所有学生对象
        Student[] students = dao.findAllStudent();
        //创建一个新的集合
        ArrayList<Student> list = new ArrayList<>();
        //遍历学生数组，把学生对象取出来放到新的集合
        for (int i = 0; i < students.length; i++) {
            Student stu = students[i];
            list.add(stu);
        }
        //创建发送到客户端的字符串
        //给集合排序
        Collections.sort(list, (stu1, stu2) -> {
            if (stu1 != null & stu2 != null) {
                return stu1.getId().compareTo(stu2.getId());
            } else {
                return 0;
            }
        });
        String str = "";
        if (list != null) {
            //拼接所有对象的字符串表示形式
            for (Student student : list) {
                str = str + "=" + student.toString();
            }
            str = str.substring(1);
        }



        //将拼接的字符串发送给客户端
        try {
            //创建一个字符缓冲输出流
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            //将服务端指定的数据str发送给客户端
            bw.write(str);
            bw.newLine();
            //刷新缓冲区
            bw.flush();
            //给服务器一个结束标记，告诉服务器文件已经传输完毕
            socket.shutdownOutput();
        } catch (IOException e) {
            System.out.println("服务端查看反馈客户端异常");
        }

    }


    //业务员中的删除功能
    public void deleteStudentById(String delId) {
        //指挥库管进行删除学生动作
        dao.deleteStudentById(delId);
    }

    //业务员的修改功能
    public void updateStudentById(String newStu) {
        //指挥库管进行修改学生信息动作
        dao.updateStudentById(newStu);

    }


    //业务员的登录功能
    public void login(String msg) throws IOException {

        String[] split = msg.split(",");
        String username = split[0];
        String password = split[1];


        //拿到库管
        OtherStudentDao osd = new OtherStudentDao();
        //叫库管先查管理员信息
        Properties prop = osd.finAllUsers();
        //拿到库管的资料信息与入口输入的进行比对
        //标记位思想：先假设人员录入的不存在
        boolean flag = false;
        //拿人员录入的和资料的是否一致，如果一致修改标记
        if (prop.containsKey(username) & password.equals(prop.getProperty(username))) {

            flag = true;

            System.out.println(username+"登录成功");


        }

        //将结果响应给客户端
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write(flag + "");
        bw.newLine();
        bw.flush();
        bw.close();
        socket.close();

    }


    @Override
    public void run() {

        try {
            //获取客户端传过来的报文数据
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String allMsg = br.readLine();


            //解析报文（业务名称&客户端传来的数据）split=login & 用户名和密码
            String[] split = allMsg.split("&");
            Option option = Enum.valueOf(Option.class, split[0]);

            //根据split[0]记录的业务名称进行对应的操作      ---业务路由
            switch (option) {
                case LOGIN:
                    login(split[1]);
                    break;
                case IS_EXISTS_STUDENT:
                    isExists(split[1]);
                    break;
                case ADD_STUDENT:
                    addStudent(split[1]);
                    break;
                case FIND_STUDENT:
                    findAllStudent();
                    break;
                case DELETE_STUDENT_BY_ID:
                    deleteStudentById(split[1]);
                    break;
                case UPDATE_STUDENT_BY_ID:
                    updateStudentById(split[1]);
                    break;


            }
        } catch (Exception e) {
            System.out.println("服务器端按报文进行业务操作异常");
        }


    }


}
